<script setup>
import * as THREE from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
// 引入UnrealBloomPass通道
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import {ref,onMounted} from 'vue'
let firstThree = ref()
const scene = new THREE.Scene()
const group = new THREE.Group()
scene.add(group)

let box = new THREE.BoxGeometry(100,100,100)
let material = new THREE.MeshBasicMaterial({
  color:"#09a"
})
let mesh = new THREE.Mesh(box,material)
let mesh1 = mesh.clone();
mesh1.position.set(200,0,0)
group.add(mesh)
group.add(mesh1)

const axeshelper = new THREE.AxesHelper(100);
scene.add(axeshelper)

// 环境光
const ambient = new THREE.AmbientLight("#fff",0.8)
scene.add(ambient)

const width = window.innerWidth;
const height = window.innerHeight;

const camera = new THREE.PerspectiveCamera(100,width/height,1,8000)
camera.position.set(-314,316,168)
camera.lookAt(10,5,0) 

// 解决渲染出来的图像有锯齿
const renderer = new THREE.WebGLRenderer({
  antialias:true
});
renderer.setSize(width,height)


// 创建一个渲染器通道，场景和相机作为参数
const renderPass = new RenderPass(scene, camera);
// 创建后处理对象EffectComposer，WebGL渲染器作为参数
const composer = new EffectComposer(renderer);
// 设置renderPass通道
composer.addPass(renderPass);

// canvas画布宽高度尺寸是800, 600
const bloomPass = new UnrealBloomPass(new THREE.Vector2(window.innerWidth, window.innerHeight));
bloomPass.strength = 2.0;
composer.addPass(bloomPass)

const controls = new OrbitControls(camera,renderer.domElement)
controls.addEventListener("change",function(){
  renderer.render(scene,camera)
})
function render(){
  requestAnimationFrame(render)
  composer.render()
}
render()
onMounted(()=>{
  let firstEle = document.getElementById("firstThree");
  firstEle.appendChild(renderer.domElement)
  firstEle.addEventListener("click",(e)=>{
    const px = e.offsetX;
    const py = e.offsetY;
    const x = (px / window.innerWidth) * 2 - 1;
    const y = -(py / window.innerHeight) * 2 + 1;

    const raycaster = new THREE.Raycaster();
    raycaster.setFromCamera(new THREE.Vector2(x,y),camera)
    const inter = raycaster.intersectObjects(scene.children);
    // inter[0] && (inter[0].object.material.color.set('#fa0'))
    inter[0] && (outline.selectedObjects = inter.map(t=>t.object))
    console.log(inter)

  })

})

</script>

<template>
  <div>
    <div id="firstThree" ref="firstThree"></div>
  </div>
</template>

<style scoped>
  #firstThree{
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    position: absolute;
  }
</style>
